import { compareSync } from 'bcryptjs';
import { PassportStrategy } from '@nestjs/passport';
import { IStrategyOptions, Strategy } from 'passport-local';
import { User } from 'src/system/user/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BadRequestException } from '@nestjs/common/exceptions';

export class LocalStorage extends PassportStrategy(Strategy) {
  constructor(@InjectRepository(User) private readonly user: Repository<User>) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    } as IStrategyOptions);
  }

  async validate(username: string, password: string) {
    const userInfo = await this.user
      .createQueryBuilder('user')
      .addSelect('user.password')
      .where('user.username=:username', { username })
      .getOne();
      
    if (!userInfo) {
      throw new BadRequestException('用户名不正确');
    }

    if (!compareSync(password, userInfo.password)) {
      throw new BadRequestException('密码错误');
    }

    return userInfo;
  }
}
